layui.use(['common'], function (common) {
    var treeTable = layui.treeTable;
    var layer = layui.layer;
    var form = layui.form;
    var admin = layui.admin,
        view = layui.view;


    var tableElem = "LAY-home-navigate-list";
    var formElem = "LAY-home-navigate-listform";
    var tableHeaderToolsElem = "LAY-home-navigate-header-tools";
    var tableToolsElem = "LAY-home-navigate-tools";
    var formSubmitElem = "LAY-home-navigate-listform-submit";

    var homePage = {};

    /**
     *  导航英文名的下拉框选择
     */
    var enNameDropdown = () => {
        var $ = layui.$;
        var dropdown = layui.dropdown
        dropdown.render({
            elem: '#enName',
            data: [
                {
                    title: 'index',
                    id: 101
                }, {
                    title: 'product',
                    id: 102
                }, {
                    title: 'solution',
                    id: 103
                }, {
                    title: 'blog',
                    id: 104
                }, {
                    title: 'cases',
                    id: 105
                }, {
                    title: 'contact',
                    id: 106
                }, {
                    title: 'about',
                    id: 107
                }, {
                    title: 'download',
                    id: 108
                }, {
                    title: 'knowledge',
                    id: 109
                }, {
                    title: 'services',
                    id: 110
                }, {
                    title: 'joinus',
                    id: 111
                }
            ],
            click: function (obj) {
                this.elem.val(obj.title);
                $("#dynamic_url").val(obj.title)
                $("#static_url").val(obj.title)
            },
            style: 'min-width: 235px;'
        });

    }

    // 渲染
    var inst = treeTable.render({
        elem: `#${tableElem}`,
        url: window.globalConfig.url_navigate_list, // 此处为静态模拟数据，实际使用时需换成真实接口
        tree: {
            /*
            // 异步加载子节点
            async: {
              enable: true,
              url: '/static/2.8/json/treeTable/demo-async.json', // 此处为静态模拟数据，实际使用时需换成真实接口
              autoParam: ["parentId=id"]
            }
            */
        },
        height: 'full-200',
        toolbar: `#${tableHeaderToolsElem}`,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', title: 'ID', width: 80, sort: true, fixed: 'left'},
            {field: 'name', title: '导航名称', width: 180, fixed: 'left', edit: 'text'},
            // {field: 'en_name', title: '导航uri', width: 180, edit: 'text'},
            // {field: 'url', title: '跳转url', width: 200, sort: true, edit: 'text'},
            {field: 'writeurl', title: '自定义URL', width: 200, sort: true, edit: 'text'},
            {field: 'vieworder', title: '排序', width: 200, sort: true, edit: 'text'},
            {
                field: 'isshow',
                title: '是否显示  ',
                width: 110,
                sort: true,
                templet: '#ID-table-navigate-isshow-switch'
            },
            {
                field: 'opennew',
                title: '是否打开新页面',
                width: 180,
                sort: true,
                templet: '#ID-table-navigate-opennew-switch'
            },
            {
                field: 'type', title: '类型', templet: function (d) {
                    if (d.type === "1") {
                        return '网页';
                    } else if (d.type === "2") {
                        return '锚点';
                    }
                }
            },
            // {
            //     field: 'is_mobile', title: '是否有手机端', width: 120, templet: '#ID-table-navigate-is_mobile-switch'
            // },

            {fixed: "right", title: "操作", width: 300, align: "center", toolbar: `#${tableToolsElem}`}
        ]],
        page: true,
        done: (res) => {
            homePage = res.data[0];
        }
    });


    function downloadFile(url) {
        var link = document.createElement('a');
        link.href = url;
        link.target = "_blank"
        link.download = 'sitemap.xml';  // 这里指定下载后的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }


    // 表头工具栏工具事件
    treeTable.on('toolbar(' + inst.config.id + ')', function (obj) {
        var config = obj.config;
        var tableId = config.id;
        var status = treeTable.checkStatus(tableId);
        // todo 批量生成静态页面
        if (obj.event === "buildHtml") { // 批量生成静态页面
            layer.confirm('确定生成静态页？', function (index) {
                var loading = layer.load(1, {
                    shade: [0.1, '#fff']
                });
                admin.req({
                    url: window.globalConfig.url_staticization + "/create?action=general",
                    type: "GET",
                    success: function (res) {
                        layer.close(loading)
                        common.ctmMsg(res.code, res.msg)
                    }
                })
            })
        } else if (obj.event === "addNav") { // 添加根节点
            admin.popup({
                title: '添加导航'
                , area: ['550px', '700px']
                , id: 'LAY-popup-content-add'
                , success: function (layero, index) {
                    view(this.id).render('home/navigate/navform').done(function () {
                        form.render(null, formElem);

                        enNameDropdown();

                        //提交
                        form.on(`submit(${formSubmitElem})`, function (data) {
                            var field = data.field; //获取提交的字段
                            field.url = field.en_name;
                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            admin.req({
                                url: window.globalConfig.url_navigate_list,
                                type: "POST",
                                data: field,
                                success: function (res) {
                                    common.ctmMsg(res.code, res.msg)
                                    inst.reloadData(); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            })
                        });
                    });
                }
            });
        } else if (obj.event === "getSitemap") { // 生成sitemap
            var loading = layer.load(1, {
                shade: [0.1, '#fff']
            });
            admin.req({
                url: window.globalConfig.url_config + "/create?action=sitemap",
                type: "GET",
                success: function (res) {
                    layer.close(loading)
                    common.ctmMsg(res.code, res.msg)
                    downloadFile(window.globalConfig.base_domain + "/sitemap_index.xml")
                }
            })
        } else if (obj.event === "preview") { // 预览页面

            // 打开预览页面
            window.open(window.globalConfig.pre_html_url + homePage['writeurl'] + ".html", "blank");


        } else if (obj.event === "publish") { // 发布网站
            var loading = layer.load(1, {
                shade: [0.1, '#fff']
            });
            admin.req({
                url: window.globalConfig.url_file + "/create",
                type: "GET",
                success: (res) => {
                    if (res.code === 0) {
                        common.ctmMsg(res.code, res.msg)
                    } else {
                        common.ctmMsg(res.code, "请先生成静态页面")

                    }
                    layer.close(loading)
                },
            })
        }
    });


    // 单元格工具事件
    treeTable.on('tool(' + inst.config.id + ')', function (obj) {
        var layEvent = obj.event; // 获得 lay-event 对应的值
        var trData = obj.data;
        if (layEvent === "detail") {  // 查看详情

            admin.popup({
                title: '查看导航'
                , area: ['550px', '700px']
                , id: 'LAY-popup-content-add'
                , success: function (layero, index) {
                    trData.mode = 'read';
                    view(this.id).render('home/navigate/navform', trData).done(function () {
                        form.render(null, formElem);
                    });
                }
            });

        } else if (layEvent === "addChild") { // 添加子导航
            admin.popup({
                title: '添加导航'
                , area: ['550px', '700px']
                , id: 'LAY-popup-content-add'
                , success: function (layero, index) {
                    view(this.id).render('home/navigate/navform').done(function () {
                        form.render(null, formElem);

                        enNameDropdown()

                        //提交
                        form.on(`submit(${formSubmitElem})`, function (data) {
                            var field = data.field; //获取提交的字段
                            field.parent_id = trData.id;
                            field.url = field.en_name;

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            admin.req({
                                url: window.globalConfig.url_navigate_list,
                                type: "POST",
                                data: field,
                                success: function (res) {
                                    common.ctmMsg(res.code, res.msg)
                                    inst.reloadData(); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            })
                        });

                    });
                }
            });

        } else if (layEvent === "updateNode") { // 更新子导航

            admin.popup({
                title: '修改导航'
                , area: ['550px', '700px']
                , id: 'LAY-popup-content-edit'
                , success: function (layero, index) {
                    view(this.id).render('home/navigate/navform', trData).done(function () {
                        form.render(null, formElem);

                        enNameDropdown()

                        //提交
                        form.on(`submit(${formSubmitElem})`, function (data) {
                            var field = data.field; //获取提交的字段
                            field.url = field.en_name;

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            admin.req({
                                url: window.globalConfig.url_navigate_list + "/" + trData.id,
                                type: "PUT",
                                data: field,
                                success: function (res) {
                                    common.ctmMsg(res.code, res.msg)
                                    inst.reloadData(); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            })
                        });

                    });
                }
            });


        } else if (layEvent === "delNode") { // 删除子导航
            layer.confirm('确定删除导航"' + trData.name + '"？', function (index) {
                admin.req({
                    url: window.globalConfig.url_navigate_list + "/" + trData.id,
                    type: "DELETE",
                    success: function (res) {
                        layer.msg(res.msg)
                        layer.close(index);
                        inst.reloadData(); //重载表格
                    }
                })
            });

        }
    });

    // 表格文本修改
    common.tableTextEditor(tableElem, window.globalConfig.url_navigate_list, 'id')

    // 表格的切换器修改
    common.tableSwitchEditor('navigate-isshow-status', window.globalConfig.url_navigate_list)
    common.tableSwitchEditor('navigate-opennew-status', window.globalConfig.url_navigate_list)
    common.tableSwitchEditor('navigate-is_mobile-status', window.globalConfig.url_navigate_list)

});
